package genericlistsvsarrays;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: gia
 * Date: 30.08.2012
 * Time: 02:19
 *
 */
public class CounterSet<T> {

    private Map<T,Integer> mapCounter;

    public CounterSet() {
        mapCounter = new HashMap<T, Integer>();
    }

    public void put(T elem){

        if(elem == null)
            throw new IllegalArgumentException("Can't add null");

        mapCounter.put(elem,getElemNumber(elem)+1);
    }

    public Integer getElemNumber(T elem){

        Integer number = mapCounter.get(elem);
        return number == null? 0:number;
    }

    T getTheElementWithTheBiggestNumberFrom(T... elements){

        T greatest = null;

        for(T elem:elements){
            if(getElemNumber(elem) > getElemNumber(greatest))
                greatest = elem;
        }

        return greatest;
    }

    /* Here is ok to surpress a warning because our keySet always contains elements of type T*/
    @SuppressWarnings("unchecked")
    T getBestElement(){
        return getTheElementWithTheBiggestNumberFrom((T[]) mapCounter.keySet().toArray());
    }

    public static void main(String[] args) {

        CounterSet<String> stringCounterSet = getSomeCounterSet();

        System.out.println(stringCounterSet.getBestElement());
        System.out.println(stringCounterSet.getTheElementWithTheBiggestNumberFrom("x","y"));


    }

    private static CounterSet<String> getSomeCounterSet() {

        CounterSet<String> stringCounterSet = new CounterSet<String>();
        stringCounterSet.put("ana");
        stringCounterSet.put("ana");
        stringCounterSet.put("ana");
        stringCounterSet.put("maria");
        return stringCounterSet;
    }

}
